﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using Common.DataTypes;
using LINQAmazonProvider;
using System.Windows.Threading;

namespace SilverlightApplication1
{
    public partial class Page : UserControl
    {
        private Dispatcher _mainDispatcher;
        private List<Common.DataTypes.Item> lstQueryResult = new List<Item>();

        // Atributo sobre el que ejecutaremos las busquedas
        // Amazon Search parameters
        private string searchKeyword; //TODO:: cambiar este atributo para que sea una estructura con toda la info
                                      //de la query a realizar.

        public List<Item> QueryResult 
        {
            get
            {
                return lstQueryResult;
            }
            set
            {
                lstQueryResult = value;
            }
        }

        //TODO:: Cambiar el tipo de la Propiedad por la estructura a definir
        public string SearchCriteria 
        {
            get
            {
                return searchKeyword;
            }
            set
            {
                searchKeyword = value;
            }
        }

        public Page()
        {
            InitializeComponent();

            //TODO::Revisar comentario no es correcto y es confuso.
            // Se crea el Searcher y se crea el evento que maneja la finalizacion de la busqueda
            // Create searcher and event to handle search finalization event
            this._mainDispatcher = MainDispatcher.Current;
            //lstQueryResult = new List<Common.DataTypes.Item>();

            //This Boolean allows to manage the Advanced Search section
            blnAvanced = true;
        }

        private Boolean blnAvanced;

        /// <summary>
        /// Search information about 'txtQuery' and load it in 'lstResult'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void SearcherFnc()
        {
            //TODO::Eliminar ya que no es necesario ya que no es siempre la misma lista
            //this.lstResult.Items.Clear();
            
            //TODO: Creacion de SearchCriteria
            // Amazon Search parameter
            string keyword = this.txtQuery.Text;
            
            try
            {
                // Perform Amazon search
                //PerformSearch(keyword);

                // Create thread to perform the amazon search
                Thread worker = new Thread(new ThreadStart(GetLINQResult));

                //TODO:: Cambiar a set de Criteria objeto con toda la info de la busqueda. (No solo Keyword)
                // Set the static parameter Keyword
                SearchCriteria = keyword; //searchKeyword = keyword;
                worker.Start();
            }

            catch (Exception ex)
            {
                // TODO manejar excepcion
            }        
        }

        //public void PerformSearch(string keyword)
        //{
        //    try
        //    {
        //        // Create thread to perform the amazon search
        //        Thread worker = new Thread(new ThreadStart(GetLINQResult));

        //        //TODO:: Cambiar a set de Criteria
        //        // Set the static parameter Keyword
        //        SearchCriteria = keyword; //searchKeyword = keyword;
        //        worker.Start();
        //    }
        //    catch (Exception e)
        //    {
        //        throw e;
        //    }
        //}

        private void GetLINQResult()
        {
            try
            {

                //TODO::esto se tiene que ir
                List<Common.DataTypes.Book> result = new List<Common.DataTypes.Book>();

                var provider = new AmazonProvider();

                var queryable = new AmazonQuery<Common.DataTypes.Item>(provider);

                var query =
                    from book in queryable
                    where
                      book.Keyword == searchKeyword
                    select book;

                query.GetEnumerator();
                //TODO:esto se tiene que ir
                foreach (var item in query)
                {
                    result.Add((Common.DataTypes.Book)item);
                    lstQueryResult.Add((Common.DataTypes.Book)item);
                }
                //Esto es erroneo la coleccion Item es readOnly el hecho de que permita agregarle creo que es un error
                //ItemCollection resultItems = new ItemCollection();
                //ListBoxItem listItem;
                //ListItemControl lstItemCtrl;
                ////TODO:: para que es el TAG????
                //int i = 0;
                //foreach (Common.DataTypes.Book b in (List<Book>)query)
                //{
                //    listItem = new ListBoxItem();
                //    lstItemCtrl = new ListItemControl();
                //    lstItemCtrl.Tag = i;
                //    lstItemCtrl.imgData.MouseLeftButtonDown += new MouseButtonEventHandler(ShowItemInformation);
                //    lstItemCtrl.imgData.Source = new BitmapImage(new Uri(b.MediumImage, UriKind.Absolute));
                //    lstItemCtrl.txtInfo1.Text = b.Author;
                //    lstItemCtrl.txtInfo2.Text = b.Title;
                //    lstItemCtrl.txtInfo3.Text = b.Publisher;
                //    lstItemCtrl.txtInfo4.Text = "Price: " + b.ListPrice.CurrencyCode + " " + b.ListPrice.FormattedPrice;
                //    listItem.Content = lstItemCtrl;
                //    resultItems.Add(listItem);
                //    i++;
                //}
                
                //Invoque the event on the UiThread
                _mainDispatcher.BeginInvoke(delegate()
                {
                    //OnSearchCompleted(new SearchCompletedEventArgs(result));
                    //TODO::Arreglar problema de tipos que retorna y aarreglar
                    SearchCompleted(result);
                });
            }
            catch (Exception e)
            {
                //TODO:: ver de hacer manejo de la excepcion o sacar
                throw e;
            }
        }

        private void SearchCompleted(List<Common.DataTypes.Book> query)
        {
            lstResult.ItemsSource = query;
            lstResult.Visibility = Visibility.Visible;
        }

        void Search_Click(object sender, EventArgs args)
        {
            SearcherFnc();
        }

        #region Metodos viejos al finalizar la busqueda
        //private void OnSearchCompleted(SearchCompletedEventArgs e)
        //{
        //    searcher_SearchCompleted(this, e);
        //}
        
        //// Function to handle search complete event
        //void searcher_SearchCompleted(object sender, SearchCompletedEventArgs e)
        //{
        //    /*this.textprueba.Text = "DESPUES DE TERMINAR: ";

        //    Common.DataTypes.Book book;
        //    foreach (Common.DataTypes.Item i in e.Result)
        //    {
        //        book = (Common.DataTypes.Book)i;
        //        textprueba.Text += book.Author + " ";
        //    }*/
            
        //    Common.DataTypes.Book b;

        //    lstQueryResult.Clear();
        //    foreach (Common.DataTypes.Item i in e.Result)
        //    {
        //        //Add the Item to our local variable
        //        lstQueryResult.Add(i);
        //    }

        //    //In future this will be relative to the page
        //    for (int Index = 0; Index<5; Index++)
        //    {
        //        b = (Common.DataTypes.Book)lstQueryResult[Index];

        //        ListBoxItem item = new ListBoxItem();
        //        ListItemControl lstItemCtrl = new ListItemControl();
        //        lstItemCtrl.Tag = Index;
        //        lstItemCtrl.imgData.MouseLeftButtonDown += new MouseButtonEventHandler(ShowItemInformation);
        //        lstItemCtrl.imgData.Source = new BitmapImage(new Uri(b.MediumImage, UriKind.Absolute));
        //        lstItemCtrl.txtInfo1.Text = b.Author;
        //        lstItemCtrl.txtInfo2.Text = b.Title;
        //        lstItemCtrl.txtInfo3.Text = b.Publisher;
        //        lstItemCtrl.txtInfo4.Text = "Price: " + b.ListPrice.CurrencyCode + " " + b.ListPrice.FormattedPrice;
        //        item.Content = lstItemCtrl;
        //        lstResult.Items.Add(item);
        //    }

        //    lstResult.Visibility = Visibility.Visible;
        //}
        #endregion

        #region UI Methods
        void txtQueryKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                SearcherFnc();
            }
        }

        void ShowItemInformation(object sender, MouseButtonEventArgs e)
        {
            //ListItemControl Item = ((ListItemControl)(((StackPanel)((Image)sender).Parent).Parent));
            ContentPresenter Item = ((ContentPresenter)(((StackPanel)((Image)sender).Parent).Parent));

            //Common.DataTypes.Book b = ((Common.DataTypes.Book)lstQueryResult[((int)Item.Tag)]);
            Common.DataTypes.Book b = ((Common.DataTypes.Book)lstQueryResult[(lstResult.Items.IndexOf(Item))]);

            imgItemInformation.Source = new BitmapImage(new Uri(b.LargeImage, UriKind.Absolute));
            txtItemInfo1.Text = b.Author;            
            txtItemInfo2.Text = b.Publisher;
            txtItemInfo3.Text = b.Title;
            
            infoItemVisible.Begin();
        }

        void CloseItemInformation(object sender, EventArgs args)
        {
            infoItemNotVisible.Begin();
        }
        
        void btnBooksToBigger(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderBigger.Stop();

            Storyboard.SetTargetName(renderBigger, "rdrBooks");
            rdrBooks.CenterX = 30;
            rdrBooks.CenterY = 30;
            renderBigger.Begin();
        }

        void btnBooksToLower(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderLower.Stop();

            Storyboard.SetTargetName(renderLower, "rdrBooks");
            renderLower.Begin();
        }

        void btnAbout1ToBigger(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderBigger.Stop();

            Storyboard.SetTargetName(renderBigger, "rdrAbout1");
            rdrAbout1.CenterX = 30;
            rdrAbout1.CenterY = 30;
            renderBigger.Begin();
        }

        void btnAbout1ToLower(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderLower.Stop();

            Storyboard.SetTargetName(renderLower, "rdrAbout1");
            renderLower.Begin();
        }

        void btnAbout2ToBigger(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderBigger.Stop();

            Storyboard.SetTargetName(renderBigger, "rdrAbout2");
            rdrAbout2.CenterX = 30;
            rdrAbout2.CenterY = 30;
            renderBigger.Begin();
        }

        void btnAbout2ToLower(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderLower.Stop();

            Storyboard.SetTargetName(renderLower, "rdrAbout2");
            renderLower.Begin();
        }

        void Advanced(object sender, EventArgs args)
        {
            if (blnAvanced)
            {
                toVisible.Begin();
            }
            else
            {
                toNotVisible.Begin();
            }
            blnAvanced = !blnAvanced;
            
        }
        
        void btnConfirmToLight(object sender, EventArgs args)
        {
            imgDarkGreen.Visibility = Visibility.Collapsed;
            imgLightGreen.Visibility = Visibility.Visible;
        }

        void btnConfirmToDark(object sender, EventArgs args)
        {
            imgDarkGreen.Visibility = Visibility.Visible;
            imgLightGreen.Visibility = Visibility.Collapsed;
        }

        void btnCancelToLight(object sender, EventArgs args)
        {
            imgDarkRed.Visibility = Visibility.Collapsed;
            imgLightRed.Visibility = Visibility.Visible;
        }

        void btnCancelToDark(object sender, EventArgs args)
        {
            imgDarkRed.Visibility = Visibility.Visible;
            imgLightRed.Visibility = Visibility.Collapsed;
        }
        #endregion
    }
}
